package com.bt7274.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bt7274.mapper.*;
import com.bt7274.pojo.*;
import com.bt7274.service.ReportService;
import com.bt7274.service.UserExpService;
import com.bt7274.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportRecordMapper reportRecordMapper;
    @Autowired
    private NotificationMapper notificationMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserExpService userExpService;
    @Autowired
    private BtTransactionMapper btTransactionMapper;

    @Override
    public void submitReport(ReportRecord reportRecord) {
        reportRecord.setReporterId(SessionUtils.getCurrentUserId());
        // 默认状态为0 未处理
        reportRecord.setStatus(0);
        reportRecordMapper.insertReport(reportRecord);
    }

    @Override
    public Page<ReportRecord> getReports(String filter, String reportedType, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        List<Integer> statuses = null;
        if(Objects.equals(filter, "pending")) {
            statuses = List.of(0); // 只查询未处理的举报
        } else if(Objects.equals(filter, "processed")) {
            statuses = List.of(1, 2); // 查询已处理的举报
        } else if(Objects.equals(filter, "all")) {
            statuses = List.of(0, 1, 2); // 查询所有举报
        }
        // 查询分页数据
        List<ReportRecord> records = reportRecordMapper.selectReports(statuses, reportedType, offset, pageSize);
        // 查询总数
        long total = reportRecordMapper.countReports(statuses, reportedType);

        // 封装Page对象
        Page<ReportRecord> pageResult = new Page<>(page, pageSize);
        pageResult.setRecords(records);
        pageResult.setTotal(total);
        return pageResult;
    }

    @Override
    public Page<ReportRecord> getReportsByReporter(String reporterId, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        List<ReportRecord>records= reportRecordMapper.selectByReporterId(reporterId, offset, pageSize);
        // 查询总数
        long total = reportRecordMapper.countByReporterId(reporterId);

        // 封装Page对象
        Page<ReportRecord> pageResult = new Page<>(page, pageSize);
        pageResult.setRecords(records);
        pageResult.setTotal(total);
        return pageResult;

    }

    @Override
    public void processReport(Long reportId, Integer status, String processResult) {
        ReportRecord report = reportRecordMapper.selectById(reportId);

        if (report == null) {
            throw new IllegalArgumentException("举报记录不存在");
        }
        try {
            String type = report.getReportedType();
            String reportedId = report.getReportedId();
            // 被举报用户通知内容
            String contentForReportedUser = "";
            // 举报人通知内容
            String contentForReporter = "";
            String notifyType = "";
            switch (type) {
                case "post" -> {
                    Post post = postMapper.selectPostById(reportedId);
                    if (post != null) {
                        contentForReportedUser = "你的帖子《" + post.getTitle() + "》被举报并已处理。";
                        contentForReporter = "你举报的帖子《" + post.getTitle() + "》";
                        notifyType = "post_report";
                    }
                }
                case "comment" -> {
                    Comment comment = commentMapper.selectCommentById(reportedId);
                    if (comment != null) {
                        contentForReportedUser = "你的评论" + comment.getContent() + "被举报并已处理。";
                        contentForReporter = "你举报的评论" + comment.getContent();
                        notifyType = "comment_report";
                    }
                }
                case "user" -> {
                    User user = userMapper.selectById(reportedId);
                    if (user != null) {
                        contentForReportedUser = "你的账户被举报并已处理。";
                        contentForReporter = "你举报的用户 " + user.getUsername();
                        notifyType = "user_report";
                    }
                }
                default -> {
                    contentForReportedUser = "被举报对象类型未知，无法生成通知。";
                    contentForReporter = "你举报的对象（未知类型）";
                    notifyType = "unknown";
                }
            }
            BtTransaction transaction = new BtTransaction();
            transaction.setId(UUID.randomUUID().toString().replace("-", ""));

            // 处理BT币奖惩
            if (status == 1) { // 举报成功
                // 被举报人扣除50BT币
                transaction.setId(UUID.randomUUID().toString().replace("-", ""));
                transaction.setUserId(reportedId);
                transaction.setPoints(-50);
                transaction.setType("REPORTED");
                transaction.setRuleId("POST");
                transaction.setDescription("帖子被举报，扣除50bt币");
                transaction.setCreatedTime(LocalDateTime.now());
                btTransactionMapper.insert(transaction);
                boolean reportedUserDeductSuccess = userExpService.updateBt(reportedId, -50);
                if (reportedUserDeductSuccess) {
                    contentForReportedUser += " 由于违规，扣除50BT币。";
                }

                // 举报人奖励30BT币
                transaction.setId(UUID.randomUUID().toString().replace("-", ""));
                transaction.setUserId(reportedId);
                transaction.setPoints(30);
                transaction.setType("REPORT");
                transaction.setRuleId("POST");
                transaction.setDescription("帖子举报成功，获得30bt币");
                transaction.setCreatedTime(LocalDateTime.now());
                btTransactionMapper.insert(transaction);
                boolean reporterRewardSuccess = userExpService.updateBt(report.getReporterId(), 30);
                if (reporterRewardSuccess) {
                    contentForReporter += " 已被成功处理，感谢你的反馈。奖励30BT币。";
                } else {
                    contentForReporter += " 已被成功处理，感谢你的反馈。但奖励BT币失败。";
                }
            } else if (status == 2) { // 举报失败
                // 举报人扣除10BT币
                transaction.setId(UUID.randomUUID().toString().replace("-", ""));
                transaction.setUserId(reportedId);
                transaction.setPoints(-10);
                transaction.setType("REPORT_FAILED");
                transaction.setRuleId("POST");
                transaction.setDescription("帖子举报失败，扣除10bt币");
                transaction.setCreatedTime(LocalDateTime.now());
                btTransactionMapper.insert(transaction);
                boolean reporterDeductSuccess = userExpService.updateBt(report.getReporterId(), -10);
                if (reporterDeductSuccess) {
                    contentForReporter += " 未被认定违规，扣除10BT币作为惩罚。";
                } else {
                    contentForReporter += " 未被认定违规，但扣除BT币失败。";
                }
            }

            // 发送通知
            if (status == 1) {
                sendNotification(reportedId, contentForReportedUser, notifyType);
                sendNotification(report.getReporterId(), contentForReporter, "report_success");
            } else if (status == 2) {
                sendNotification(report.getReporterId(), contentForReporter, "report_failed");
            }

            // 更新举报处理结果
            reportRecordMapper.updateReportProcess(reportId, status, processResult, new Date());
        } catch (Exception e) {
            throw new RuntimeException("处理举报失败：" + e.getMessage());
        }
    }

    /**
     * 统一封装通知发送
     */
    private void sendNotification(String receiverId, String content, String type) {
        Notification notification = new Notification();
        notification.setReceiverId(receiverId);
        notification.setContent(content);
        notification.setSenderId(SessionUtils.getCurrentUserId()); // 当前处理举报的管理员
        notification.setType(type);
        notification.setCreatedTime(LocalDateTime.now());
        notificationMapper.insertNotification(notification);
    }
}
